package main

import (
	"fmt"
	"image"
	"image/color"
	"image/png"
	"math"
	"net/http"
	"time"
)

type pointSet struct {
	r       uint8
	g       uint8
	b       uint8
	thick   uint8
	sets    [][2]int
	origin  [2]int
	pixperx int
	pixpery int
	xwidth  int
	ywidth  int
}

func newPointSet(x, y int) *pointSet {
	var ps pointSet
	ps.xwidth = x
	ps.ywidth = y
	ps.pixperx = 30
	ps.pixpery = 60
	ps.origin[0] = 20
	ps.origin[1] = ps.ywidth / 2
	return &ps
}

func (ps *pointSet) draw(img *image.NRGBA, rset [][2]float64) {
	ps.genSets(rset)
	ps.drawOrigin(img)
	ps.drawXaxis(img)
	ps.drawYaxis(img)
	for idx := range ps.sets {
		fmt.Println(ps.sets[idx])
		img.Set(ps.sets[idx][0], ps.sets[idx][1], color.RGBA{ps.r, ps.g, ps.b, 255})
		img.Set(ps.sets[idx][0], ps.sets[idx][1]-1, color.RGBA{ps.r, ps.g, ps.b, 255})
	}
}

func (ps *pointSet) genSets(rset [][2]float64) {
	l := len(rset)
	ps.sets = make([][2]int, l, l)
	for idx := range rset {
		gx := ps.origin[0] + int(rset[idx][0]*float64(ps.pixperx))
		gy := ps.origin[1] - int(rset[idx][1]*float64(ps.pixpery))
		ps.sets[idx][0] = gx
		ps.sets[idx][1] = gy
	}
}

func (ps *pointSet) drawOrigin(img *image.NRGBA) {
	img.Set(ps.origin[0], ps.origin[1], color.RGBA{ps.r, ps.g, ps.b, 255})
	img.Set(ps.origin[0]+1, ps.origin[1], color.RGBA{ps.r, ps.g, ps.b, 255})

}

func (ps *pointSet) drawXaxis(img *image.NRGBA) {
	for x := ps.origin[0]; x < ps.xwidth-ps.pixperx*3; x++ {
		for y := ps.origin[1]; y < ps.origin[1]+1; y++ {
			img.Set(x, y, color.RGBA{ps.r, ps.g, ps.b, 255})
		}
	}
}

func (ps *pointSet) drawYaxis(img *image.NRGBA) {
	for y := 20; y < ps.ywidth-20; y++ {
		for x := ps.origin[0]; x < ps.origin[0]+1; x++ {
			img.Set(x, y, color.RGBA{ps.r, ps.g, ps.b, 255})
		}
	}
}

func pic(w http.ResponseWriter, req *http.Request) {
	const (
		dx = 600
		dy = 400
	)

	// 新建一个 指定大小的 RGBA位图
	img := image.NewNRGBA(image.Rect(0, 0, dx, dy))

	//
	rset := make([][2]float64, 660, 660)
	// for idx := range rset {
	// 	rx := float64(idx + 1)
	// 	ry := float64(idx + 1)
	// 	rset[idx][0] = rx
	// 	rset[idx][1] = ry
	// }

	for idx := range rset {
		rx := float64(idx) * (0.02)
		ry := math.Sin(rx)
		rset[idx][0] = rx
		rset[idx][1] = ry
	}

	fmt.Println(rset)

	ps := newPointSet(dx, dy)
	ps.draw(img, rset)
	// 图片流方式输出
	w.Header().Set("Content-Type", "image/png")
	png.Encode(w, img)
	fmt.Println("d")
}

func main() {
	http.HandleFunc("/d", pic)
	s := &http.Server{
		Addr:           ":8888",
		ReadTimeout:    30 * time.Second,
		WriteTimeout:   30 * time.Second,
		MaxHeaderBytes: 1 << 20}
	d := s.ListenAndServe()
	fmt.Println(d)
}
